<template>
    <div>
        <!-- 条件渲染：当商品列表为空时显示 van-empty -->
        <van-empty v-if="cartItems.length === 0" description="您还没有加入商品" />

        <!-- 当有商品时显示商品列表 -->
        <template v-else>
            <van-swipe-cell v-for="item in cartItems" :key="item.id">
                <div class="cart-item">
                    <div class="item-checkbox">
                        <van-checkbox v-model="item.checked" />
                    </div>

                    <van-card :num="item.quantity" :price="item.price" :title="item.title" class="goods-card"
                        :thumb="item.thumb">
                        <template #bottom>
                            <div class="maths">
                                <button class="btn minus" @click="decrease(item)" :disabled="item.quantity <= 1"
                                    :class="{ disabled: item.quantity <= 1 }">-</button>
                                <input type="number" v-model.number="item.quantity" @change="validateQuantity(item)"
                                    class="input" min="1">
                                <button class="btn plus" @click="increase(item)">+</button>
                            </div>
                        </template>
                    </van-card>
                </div>

                <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="removeItem(item.id)" />
                </template>
            </van-swipe-cell>

            <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit" class="submit-bar">
                <van-checkbox v-model="allChecked" @click="toggleAll">全选</van-checkbox>
                <button>批量删除</button>
            </van-submit-bar>
        </template>
    </div>
</template>

<script setup>
import { ref, computed } from "vue";  // 确保导入 computed
import { showToast } from 'vant';

// 购物车商品数据
const cartItems = ref([
    {
        id: 1,
        title: "示例商品",
        price: "99.00",
        thumb: "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg",
        quantity: 1,
        checked: false
    }

]);


const onSubmit =()=>{}

// 全选状态
const allChecked = ref(false);


// 计算总价（只计算选中的商品）
const totalPrice = computed(() => {
    return cartItems.value.reduce((total, item) => {
        return item.checked ? total + (parseFloat(item.price) * item.quantity * 100) : total;
    }, 0);
});


// 全选/取消全选
const toggleAll = () => {
    cartItems.value.forEach(item => {
        item.checked = allChecked.value;
    });
};

// 数量减少
const decrease = (item) => {
    if (item.quantity > 1) {
        item.quantity--;
    }
};

// 数量增加
const increase = (item) => {
    item.quantity++;
};

// 验证数量
const validateQuantity = (item) => {
    if (item.quantity < 1 || isNaN(item.quantity)) {
        item.quantity = 1;
    }
};

</script>

<style scoped>
@import url(../../assets/css/Car.css);
</style>
